﻿using MediatR;
using W.Purchase.Domain.PageDTO;
using W.Purchase.Read.API.AppLication.Command.Command;
using W.Purchase.Repository.Interface;
using W.Device.Domain.DTO;
namespace W.Purchase.Read.API.AppLication.Command.CommandHandler
{
    public class UnitShowCommandHandler : IRequestHandler<UnitShowCommand, PageDTO<Domain.Unit>>
    {
        private readonly IUnitRepository repository;
        public UnitShowCommandHandler(IUnitRepository repository)
        {
            this.repository = repository;
        }

        public async Task<PageDTO<Domain.Unit>> Handle(UnitShowCommand request, CancellationToken cancellationToken)
        {
            PageDTO<Domain.Unit> dto = new PageDTO<Domain.Unit>();   
            var list = await repository.GetAsync(x => x.IsDelete == false);
            if (!string.IsNullOrEmpty(request.UnitNo))
            {
                list = list.Where(x => x.UnitNo == request.UnitNo).ToList();
            }
            if (!string.IsNullOrEmpty(request.UnitName))
            {
                list = list.Where(x => x.UnitName.Contains(request.UnitName)).ToList();
            }
            dto.TotalCount = list.Count();
            dto.TotalPage = (int)Math.Ceiling(dto.TotalCount * 1.0 / request.pageSize);
            dto.List = list.OrderByDescending(x=>x.CreateTime).Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
            return dto;
        }
    }
}
